<!-- My Bots -->
<!-- Author: Edwin -->
<template>
  <el-card shadow="never"
           class="aui-card--fill">
    <add-or-update v-if="addOrUpdateVisible"
                   ref="addOrUpdate"
                   @refreshDataList="getDataList"></add-or-update>
    <div>
      <el-form :inline="true">
        <el-form-item>
          <el-button type="primary"
                     size="small"
                     @click="addOrUpdateHandle()">{{ $t('add') }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning"
                     size="small"
                     @click="batchGenerateDataset()">{{ 'Batch Generate Dataset' }}
          </el-button>
        </el-form-item>
      </el-form>
      <div class="control-section">
        <div class="content-wrapper"
             v-loading="loading">
          <ejs-grid :dataSource="dataList"
                    :allowResizing='gridDefaultSetting.allowResizing'
                    :allowFiltering='gridDefaultSetting.allowFiltering'
                    :filterSettings='gridDefaultSetting.filterSettings'
                    :allowGrouping='true'
                    :allowPaging='true'
                    :toolbar="gridDefaultSetting.toolbar"
                    :allowTextWrap="gridDefaultSetting.allowTextWrap"
                    :showColumnChooser='gridDefaultSetting.showColumnChooser'
                    :allowReordering='gridDefaultSetting.allowReordering'
                    :allowSorting='true'
                    :editSettings='editSettings'
                    v-loading='dataListLoading'
                    ref="grid"
                    height="56vh"
                    class="sortingenabled"
                    :selectionSettings='gridDefaultSetting.selectOptions'
                    :commandClick='commandClick'
                    :rowSelected='dataListSelectionChangeHandle'
                    :pageSettings='pageSettings'
                    :showColumnMenu='gridDefaultSetting.showColumnMenu'>
            <e-columns>
              <e-column field='name'
                        headerText="API Name"
                        :width='120'></e-column>
              <e-column field='syncClient'
                        headerText="Sync Client"
                        :width='120'></e-column>
              <e-column field='syncPath'
                        headerText="Sync Path"
                        :width='120'></e-column>
              <e-column field='syncOpen'
                        headerText="Sync Open"
                        :width='120'></e-column>
              <e-column field='deleteOpen'
                        headerText="Delete Open"
                        :width='120'></e-column>
              <e-column field='client'
                        :headerText="$t('custom.botStore.client')"
                        :width='120'></e-column>
              <!-- <e-column field='method'
                        :headerText="$t('custom.botStore.method')"
                        :width='80'></e-column> -->
              <e-column field='sourceMapping'
                        :headerText="$t('custom.botStore.sourceMapping')"
                        :width='120'></e-column>
              <e-column field='prodMapping'
                        :headerText="$t('custom.botStore.prodMapping')"
                        :width='90'></e-column>
              <e-column field='prodMappingType'
                        :headerText="$t('custom.botStore.prodMappingType')"
                        :width='110'></e-column>
              <e-column field='action'
                        :headerText="$t('custom.botStore.action')"
                        :width='80'></e-column>
              <e-column field='deleteAction'
                        headerText="Delete Action"
                        :width='80'></e-column>
              <!-- <e-column field='apiService'
                        :headerText="$t('custom.botStore.apiService')"
                        :width='80'></e-column> -->
              <e-column field='isShow'
                        :headerText="$t('custom.botStore.isShow')"
                        :width='120'
                        :template="isShowFormat"></e-column>
              <e-column field='linkedDataset'
                        :headerText="$t('custom.dataset.linkedDatasetbtn')"
                        :template="LinkedDatasetBtn"
                        textAlign='Center'
                        :width='120'></e-column>
              <e-column :template="CreateTimeFormat"
                        :headerText="$t('custom.botStore.createTime')"
                        field='createDate'
                        :width='120'></e-column>
              <e-column :template="UpdateTimeFormat"
                        field='updateDate'
                        :headerText="$t('custom.botStore.updateTime')"
                        :width='120'></e-column>
              <!-- <e-column
                        :template="LastUpdateDateFormat"
                        field='lastUpdateDate'
                        :headerText="$t('custom.botStore.lastupdatedate')"
                        :width='120'></e-column> -->
              <e-column field='lastSyncDate'
                        :template="LastSyncDateFormat"
                        :headerText="$t('custom.botStore.lastsyncdate')"
                        :width='120'></e-column>
              <e-column :headerText="$t('customize')"
                        :template="ApiManagerBtn"
                        :width='180'
                        textAlign='Right'></e-column>
            </e-columns>
          </ejs-grid>

                <linked-dataset v-if="linkDatasetVisible"
                        ref="linkDataset"
                        @refreshDataList="getDataList"></linked-dataset>
        </div>
      </div>
    </div>
  </el-card>
</template>
<script>
import Vue from 'vue'

import mixinViewModule from '@/mixins/crud-view-module'
import AddOrUpdate from './add-or-update'
import CreateTimeFormat from './FormatComponents/CreateTimeFormat'
import UpdateTimeFormat from './FormatComponents/UpdateTimeFormat'
import LastUpdateDateFormat from './FormatComponents/LastUpdateDateFormat'
import LastSyncDateFormat from './FormatComponents/LastSyncDateFormat'
import isShowFormat from './FormatComponents/isShowFormat'
import { LinkComponent } from './FormatComponents/LinkComponent.js'
import LinkedDataset from '../../../../../components/linked-dataset/src/linked-dataset.vue'

export default {
  mixins: [mixinViewModule],
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListIsPage: false,
        activatedIsNeed: false,
        createdIsNeed: false
      },
      dataForm: {},
      scope: [],
      loading: false,

      editSettings: {
        allowDeleting: false,
        allowAdding: false,
        mode: 'Cell'
      },
      pageSettings: { pageSize: 30, pageSizes: [30, 50, 100, 1000], pageCount: 2 },
      CreateTimeFormat: function () {
        return { template: CreateTimeFormat }
      },
      UpdateTimeFormat: function () {
        return { template: UpdateTimeFormat }
      },
      LastUpdateDateFormat: function () {
        return { template: LastUpdateDateFormat }
      },
      LastSyncDateFormat: function () {
        return { template: LastSyncDateFormat }
      },
      isShowFormat: function () {
        return { template: isShowFormat }
      },
      dataList: [],
      ApiManagerBtn: function () {
        return { template: ApiManagerBtn }
      },
      LinkedDatasetBtn: function () {
        return { template: LinkedDatasetBtn }
      },
      linkDatasetVisible: false
    }
  },
  components: {
    AddOrUpdate,
    LinkedDataset

  },
  props: {},

  computed: {},
  created () {
    this.init()
    LinkComponent.$on('initPageList', () => {
      this.getDataList()
    })
  },
  methods: {
    init () {
      this.getDataList()
      Vue['_this_api_manager'] = this
    },
    async getDataList () {
      const { data: res } = await this.$interface.apiManager.queryApiManegreListApi()
      if (res.code === 0) {
        this.dataList = res.data
      } else {
      }
    },
    commandClick (type, row) {
      if (type === 'Delete') {
        if (row.linkedDataset > 0) {
          this.showLinkedDatasteDialog(row.id)
        } else {
          this.deleteHandle(row.id)
        }
      }
      if (type === 'Edit') {
        this.addOrUpdateHandle(row.id)
      }
      if (type === 'LinkeDataset') {
        this.showLinkedDatasteDialog(row.id)
      }
    },
    showLinkedDatasteDialog (id) {
      this.linkDatasetVisible = true
      this.$nextTick(() => {
        this.$refs['linkDataset'].dataForm.apiList = id
        this.$refs['linkDataset'].init()
      })
    },
    deleteHandle (id) {
      this.$confirm(this.$t('prompt.info', { 'handle': this.$t('delete') }), this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        const requestFunc = () => {
          let params = {
            id: id
          }
          return this.$interface.apiManager.deleteApiManegreApi(params)
        }
        requestFunc().then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.ms)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.getDataList()
            }
          })
        }).catch(() => {
        })
      })
    },
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.dataForm.id = id
        this.$refs.addOrUpdate.init()
      })
    },
    batchGenerateDataset () {
      this.$confirm('Please confirm to start this batch operation!', this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        this.$interface.reports.postBatchGenerateDataset().then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.ms)
          }
          this.$message.success(this.$t('prompt.success'))
        }).catch(() => {
        })
      })
    }
  },
  destroyed () {
    delete Vue['_this_api_manager']
  }
}
const LinkedDatasetBtn = Vue.component(
  'linked-botbtn', {
    template: `<el-link size="mini" :underline="false" :type="DatasetNum($data.data.linkedDataset)"  @click="clickSelect('LinkeDataset',$data.data)">{{$data.data.linkedDataset}}</el-link>`,
    data () {
      return {}
    },
    methods: {
      clickSelect (e, row) {
        Vue['_this_api_manager'].commandClick(e, row)
      },
      DatasetNum (row) {
        if (row > 0) {
          return 'success'
        } else {
          return 'danger'
        }
      }
    }
  }
)
const ApiManagerBtn = Vue.component(
  'apiManager-btn', {
    template: `<div style="display: flex;justify-content: flex-end;">
      <el-button size="mini" plain type="primary" @click="clickSelect('Edit',$data.data)">Edit</el-button>
      <el-button size="mini" plain type="danger"  @click="clickSelect('Delete',$data.data)">Delete</el-button>    
    </div>`,
    data () {
      return {}
    },
    methods: {
      clickSelect (e, row) {
        Vue['_this_api_manager'].commandClick(e, row)
      }
    }
  }
)
</script>
<style scoped>
.content-wrapper ::v-deep .sortingenabled {
  margin-top: 0px;
}
.e-grid .e-columnheader.e-wrap .e-fltr-icon .e-sortfilterdiv,
.e-grid.e-wrap .e-columnheader .e-fltr-icon .e-sortfilterdiv {
  margin: -28px 8px -29px 0;
}
</style>
